<template>
  <Card :bordered="false">
    <p slot="title">
      <Icon type="ios-paper"></Icon>
      我的工单
    </p>
    <a href="#" v-if="permission.work_order_create === '1'" slot="extra" @click.prevent="createModal=true">
      <Icon type="md-add-circle"></Icon>
      创建
    </a>
    <Modal v-model="createModal" draggable scrollable title="新建工单" :footer-hide=true>
      <Form ref="formCreate" :model="formCreate" :rules="ruleCreate" :label-width="80">
        <FormItem label="工单名称" prop="order_name">
          <Input v-model="formCreate.order_name" placeholder="Enter your new env order"></Input>
        </FormItem>
        <FormItem label="工单类型" prop="order_type">
          <Select v-model="formCreate.order_type" placeholder="Select your work type">
            <Option value="deploy">应用发布</Option>
          </Select>
        </FormItem>
        <FormItem label="应用环境" prop="env">
          <Select v-model="formCreate.env" placeholder="Select your work type">
            <Option value="prod">生产环境</Option>
          </Select>
        </FormItem>
        <FormItem label="审核人" prop="audit_user">
          <Select v-model="formCreate.audit_user" placeholder="Select your work order audit user">
            <Option value="admin">管理员</Option>
          </Select>
        </FormItem>
        <FormItem label="预计日期">
          <Row>
            <Col span="12">
              <FormItem prop="plan_time">
                <DatePicker type="datetime" format="yyyy年MM月dd日 HH点:mm分"  placeholder="Select datetime" v-model="formCreate.plan_time"></DatePicker>
              </FormItem>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="工单说明" prop="order_desc">
          <Input v-model="formCreate.order_desc" type="textarea" :autosize="{minRows: 2,maxRows: 10}" placeholder="此处填写需要发布的应用名称"></Input>
        </FormItem>
        <FormItem>
          <Button type="success" @click="createOrder('formCreate')" style="margin-left: 50px">点击提交</Button>
          <Button type="warning" @click="handleReset('formCreate')" style="margin-left: 10px">清空</Button>
          <Button type="info" @click="closeView('formCreate')" style="margin-left: 10px">关闭</Button>
        </FormItem>
      </Form>
    </Modal>
    <Table border :columns="columns" :data="data">
      <template slot-scope="{ row, index }" slot="status">
        <span v-if="`${row.status}`=='false'" style="color:#ed4014">待审核</span>
        <span v-else style="color:#19be6b">已审核</span>
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <template v-if="permission.work_order_audit === '1'">
          <Button v-if="`${row.status}`==='true'" disabled size="small" >已审核</Button>
          <Button v-else type="info" size="small" @click="update(index)">审核</Button>
        </template>
        <Button type="error" size="small" @click="remove(index)" style="margin-left:8px">删除</Button>
      </template>
    </Table>
    <div style="padding-top: 10px;" v-if="count">
      <template>
        <Page :total="count" show-total :page-size-opts="[10,25,40,55,70,100]" current.sync="current" show-elevator show-sizer @on-change="switchPage" @on-page-size-change="switchPageSize" />
      </template>
    </div>
  </Card>
</template>

<script>
import { orderList, orderCreate, orderDelete, orderUpdate } from '@/api/work-order'

  export default {
    data () {
      return {
        count: '',
        page: 1,
        pageSize: 10,
        createModal: false,
        permission: '',
        formCreate: {
          order_name: '',
          order_type: '',
          env: '',
          audit_user: '',
          plan_time: '',
          order_desc: ''
        },
        ruleCreate: {
          order_name: [
            { required: true, message: 'The name cannot be empty', trigger: 'blur' }
          ],
          order_type: [
            { required: true, message: 'Please select the work order', trigger: 'change' }
          ],
          env: [
            { required: true, message: 'Please select the env', trigger: 'change' }
          ],
          audit_user: [
            { required: true, message: 'Please select  audit user', trigger: 'change' }
          ],
          date: [
            { required: true, type: 'date', message: 'Please select the date', trigger: 'change' }
          ],
          time: [
            { required: true, type: 'string', message: 'Please select time', trigger: 'change' }
          ],
          order_desc: [
            { required: true, message: 'Please enter a personal introduction', trigger: 'blur' },
            { type: 'string', min: 2, message: 'Introduce no less than 20 words', trigger: 'blur' }
          ]
        },
        columns: [
          {
            title: '工单名称',
            key: 'order_name'
          },
          {
            title: '工单类型',
            key: 'order_type'
          },
          {
            title: '工单说明',
            key: 'order_desc'
          },
          {
            title: '提交人',
            key: 'submit_user'
          },
          {
            title: '审核人',
            key: 'audit_user'
          },
          {
            title: '审核状态',
            key: 'status',
            slot: 'status'
          },
          {
            title: '审核日期',
            key: 'audit_time'
          },
          {
            title: '创建日期',
            key: 'create_time'
          },
          {
            title: '操作',
            slot: 'action',
            width: 200,
            align: 'center'
          }
        ],
        data: []
      }
    },
    methods: {
      // 获取缓存数据
      data_list () {
        orderList(this.page,this.pageSize).then(res => {
          this.count = res.data.count
          this.data = res.data.results
        });
      },
      // 获取页码并发起请求
      switchPage (page) {
        this.page = page
        this.IngressData()
      },
      // 获取选择切换的每页条数并发起请求
      switchPageSize (pageSize) {
        this.page = 1
        this.pageSize = pageSize
        this.IngressData()
      },
      closeView (name) {
        this.createModal = false;
        this.handleReset(name);
      },
      createOrder (name) {
        // 请求后端接口创建数据
        this.$refs[name].validate((valid) => {
          if (valid) {
            // 请求后端接口创建数据
            orderCreate(this.formCreate).then(res => {
              this.data_list()  //在创建新地址时再次请求数据
              this.$Message.success({content:'创建成功!',duration: 5,closable: true});
            }).catch( err => {
              this.$Message.error({content:'创建失败!',duration: 5,closable: true})
            })
          }
        })
      },
      // 清空表单
      handleReset (name) {
        this.$refs[name].resetFields();
      },
      // 审核工单
      update (index) {
        this.$Modal.confirm({
          title: "工单审核",
          content: `<p>工单审核后会将工单状态变更为正常，是否继续？</p>`,
          onOk: () => {
            var data = {
              'status': true
            }
            orderUpdate(this.data[index].id,data).then(res => {
              this.data_list()
              this.$Message.success({content:'已审核!',duration: 5,closable: true});
            })
          },
          onCancel: () => {
            this.$Message.info('已取消审核');
          }
          })
      },
      // 删除
      remove (index) {
        this.$Modal.confirm({
          title: "警告!",
          content: `<p>删除工单后无法恢复，是否继续？</p>`,
          onOk: () => {
            orderDelete(this.data[index].id).then(res => {
              this.data.splice(index, 1);
              this.$Message.success({content:'删除成功!',duration: 5,closable: true});
            }).catch(err => {
              this.$Message.error({content:'删除失败!',duration: 5,closable: true});
            })
          },
          onCancel: () => {
            this.$Message.info('已取消删除');
          }
        })
      },
      // 获取用户操作权限
      get_permission () {
        const auth = JSON.parse(sessionStorage.getItem('permission'))
        this.permission = auth.child
      }
    },
    created () {
      this.data_list();
      this.get_permission();
    },
  }
</script>